<template>
  <a-modal v-model:open="visible.value" title="编辑课程" ok-text="确认" cancel-text="取消" @ok="onOk" @cancel="formRef.resetFields()
  emit('update:modelVisible', false);" :maskClosable="false" width="50vw">
    <a-form :rules="rules" :label-col="labelCol" ref="formRef" :model="formState" layout="horizontal"
      name="form_in_modal">
      <a-row>
        <a-col :span="12"> <a-form-item name="course_name" label="课程名称">
            <a-input v-model:value="formState.course_name" />
          </a-form-item></a-col>
        <a-col :span="12"> <a-form-item name="college" label="学院">
            <a-select v-model:value="formState.college" :options="options2"></a-select>
          </a-form-item></a-col>
      </a-row>

      <a-row justify="space-between">
        <a-col :span="12"> <a-form-item name="course_type" label="课程类型">
            <a-radio-group v-model:value="formState.course_type">
              <a-radio value="1">理论课程</a-radio>
              <a-radio value="2">实训课程</a-radio>
            </a-radio-group> </a-form-item></a-col>
        <a-col :span="12"> <a-form-item name="periods" label="课时">
            <a-input type="number" v-model:value="formState.periods"></a-input>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item name="project" label="关联项目">
        <a-select v-model:value="formState.project" mode="multiple" :fieldNames="{ label: 'project_name', value: 'project_id' }"
          :default-active-first-option="false" :show-arrow="true" :filter-option="filterOption"
          @focus="handleSearch" :options="project"></a-select>
      </a-form-item>

      <a-form-item name="project_module" label="项目模块">
        <a-select v-model:value="formState.project_module" @focus="findModule" mode="multiple" :show-arrow="true">
          <a-select-opt-group v-for="project in project_module" :key="project.project_id" :label="project.project_name">
            <a-select-option v-for="module in project.module" :key="module.module_id" :value="module.module_id">{{ module.module_name
              }}</a-select-option>
          </a-select-opt-group>
        </a-select>
      </a-form-item>
      
      <a-row justify="space-between">
        <a-col :span="9">
          <a-form-item label="上课时间" name="semester">
            <a-select v-model:value="formState.semester" placeholder="选择学期" :options="semester"></a-select>
          </a-form-item>
        </a-col>

        <a-col :span="7">
          <a-form-item name="course_startTime">
            <a-date-picker show-time v-model:value="formState.course_startTime" placeholder="开始时间" />
          </a-form-item>
        </a-col>

        <a-col :span="7">
          <a-form-item name="course_endTime">
            <a-date-picker show-time v-model:value="formState.course_endTime" placeholder="结束时间" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, toRaw, computed, onMounted, watch } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import type { Rule } from 'ant-design-vue/es/form';
import CourseDao from '@/daos/course_dao';
import ProjectDao from '@/daos/project_dao';
import { message } from 'ant-design-vue';
import { useStore } from 'vuex';

const store = useStore();
const courseDao = new CourseDao();
const projectDao = new ProjectDao();

//控制窗口打开状态
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  courseId: {
    type: Number,
    required: true
  },
  courseData: {
    type: Object,
    default: () => ({})
  }
});

const visible = computed(() => {
  return ref(props.modelVisible)
});

const emit = defineEmits(['update:modelVisible', 'course-updated']);
const labelCol = { style: { width: '90px' } };

const semester = [
  {
    value: 1,
    label: '2023-2024第一学期',
  },
  {
    value: 2,
    label: '2023-2024第二学期',
  },
  {
    value: 3,
    label: '2024-2025第一学期',
  },
  {
    value: 4,
    label: '2024-2025第二学期'
  }
];

//学院
const options2 = [
  {
    value: '1',
    label: '计算机工程学院',
  },
  {
    value: '2',
    label: '大数据学院',
  },
  {
    value: '3',
    label: '管理学院',
  },
];

//项目数据
const project = ref([]);

//点击收缩框获取项目数据
const handleSearch = () => {
  projectDao.findProjects(store.getters.userId, null, null, null, null, 0, 100)
    .then(result => {
      if (result && result.data && result.data.code === 200) {
        project.value = result.data.data.rows.map(item => ({
          project_id: item.projectId,
          project_name: item.projectName
        }));
      } else {
        project.value = [
          {
            project_id: 1111,
            project_name: '项目式教学',
          },
          {
            project_id: 1112,
            project_name: '虚拟学院',
          },
        ];
      }
    }).catch(error => {
      console.error('获取项目列表失败', error);
      // 使用测试数据作为备选
      project.value = [
        {
          project_id: 1111,
          project_name: '项目式教学',
        },
        {
          project_id: 1112,
          project_name: '虚拟学院',
        },
      ];
    });
};

//项目搜索筛选
const filterOption = (input: string, option: any) => {
  return option.project_name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

//选择项目后触发
const project_module = ref([]);
const findModule = () => {
  // 这里可以通过API获取项目模块，现在使用测试数据
  project_module.value = [{
    project_id: 1111,
    project_name: '项目式教学',
    module: [{
      module_id: 1113546,
      module_name: "数据库设计"
    }, {
      module_id: 1113547,
      module_name: "页面设计"
    }, {
      module_id: 1113548,
      module_name: "前端开发"
    }, {
      module_id: 111359,
      module_name: "后端开发"
    },]
  }, {
    project_id: 1112,
    project_name: '虚拟教研室',
    module: [{
      module_id: 111354611,
      module_name: "数据库设计"
    }, {
      module_id: 11135471,
      module_name: "页面设计"
    }, {
      module_id: 11135481,
      module_name: "前端开发"
    }, {
      module_id: 1113591,
      module_name: "后端开发"
    },]
  }];
};

interface Values {
  course_name: string;
  course_type: string;
  periods: number;
  college: string;
  semester: string;
  project: any[];
  project_module: any[];
  course_startTime: dayjs.Dayjs;
  course_endTime: dayjs.Dayjs;
}

const formRef = ref<FormInstance>();

const formState = reactive<Values>({
  course_name: '',
  course_type: '',
  periods: null,
  semester: '',
  college: '',
  project: [],
  project_module: [],
  course_startTime: null,
  course_endTime: null,
});

// 监听courseData变化，更新表单
watch(() => props.courseData, (newVal) => {
  if (newVal && Object.keys(newVal).length > 0) {
    initFormData(newVal);
  }
}, { immediate: true, deep: true });

// 初始化表单数据
const initFormData = (data: any) => {
  console.log('初始化表单数据:', data);
  if (!data) return;
  
  formState.course_name = data.courseName || '';
  
  // 解析课程描述提取信息
  const description = data.courseDescription || '';
  
  // 提取课程类型
  if (description.includes('理论课程')) {
    formState.course_type = '1';
  } else if (description.includes('实训课程')) {
    formState.course_type = '2';
  }
  
  // 提取课时
  const periodsMatch = description.match(/(\d+)学时/);
  formState.periods = periodsMatch ? parseInt(periodsMatch[1]) : null;
  
  // 提取学院
  if (description.includes('计算机工程学院')) {
    formState.college = '1';
  } else if (description.includes('大数据学院')) {
    formState.college = '2';
  } else if (description.includes('管理学院')) {
    formState.college = '3';
  }
  
  // 设置项目
  if (data.projectList && data.projectList.length > 0) {
    formState.project = data.projectList.map((item: any) => item.projectId);
  }
  
  // 获取项目数据
  handleSearch();
};

// 组件挂载时获取课程详情
onMounted(() => {
  if (props.courseId) {
    // 这里假设已经通过props.courseData传入了课程数据
    // 如果需要重新获取，可以添加获取课程详情的API调用
  }
});

const onOk = () => {
  formRef.value
    .validateFields()
    .then(async values => {
      console.log('Received values of form: ', values);
      const formData = toRaw(formState);
      
      // 确保project字段是数组形式
      if (!formData.project) {
        formData.project = [];
      } else if (!Array.isArray(formData.project)) {
        formData.project = [formData.project];
      }
      
      // 确保字段值有效
      if (!formData.course_name || formData.course_name.trim() === '') {
        message.error('课程名称不能为空');
        return;
      }
      
      try {
        // 创建新的数据对象进行提交
        const submitData: Record<string, any> = {};
        
        // 基本信息
        submitData.course_name = formData.course_name;
        submitData.course_type = formData.course_type || '';
        submitData.periods = formData.periods || 0;
        submitData.college = formData.college || '';
        submitData.semester = formData.semester || '';
        submitData.project = formData.project || [];
        submitData.project_module = formData.project_module || [];
        
        // 转换日期格式
        if (formData.course_startTime) {
          submitData.course_startTime = formData.course_startTime.format('YYYY-MM-DD HH:mm:ss');
        } else {
          submitData.course_startTime = '';
        }
        
        if (formData.course_endTime) {
          submitData.course_endTime = formData.course_endTime.format('YYYY-MM-DD HH:mm:ss');
        } else {
          submitData.course_endTime = '';
        }
        
        console.log('发送的课程数据:', submitData);
        const jsonData = JSON.stringify(submitData);
        console.log('更新的课程数据 JSON 字符串:', jsonData);
        
        const result = await courseDao.updateCourse({
          courseData: jsonData,
          courseId: props.courseId
        });
        
        console.log('服务器返回结果:', result);
        
        if (result && result.data && result.data.code === 200) {
          message.success('课程更新成功');
          emit('course-updated'); // 发出更新成功事件
          emit('update:modelVisible', false);
          formRef.value.resetFields();
        } else {
          message.error(result?.data?.msg || '更新课程失败');
          console.error('更新课程失败，服务器响应:', result);
        }
      } catch (error) {
        console.error('更新课程错误:', error);
        message.error('更新课程失败: ' + (error.message || '未知错误'));
      }
    })
    .catch(info => {
      console.log('Validate Failed:', info);
    });
};

//表单验证
const rules: Record<string, Rule[]> = {
  course_name: [
    { required: true, message: '课程名不能为空', trigger: 'blur' },
  ],
  college: [{ required: true, message: '请选择学院', trigger: 'blur' }],
  course_type: [{ required: true, message: '请选择课程类型', trigger: 'blur', }],
  periods: [{ required: true, message: '请填写课时', trigger: 'blur' }],
  semester: [{ required: true, message: '请选择学期', trigger: 'blur', }],
};
</script>

<style scoped>
.collection-create-form_last-form-item {
  margin-bottom: 0;
}
</style> 